package com.example.blueconn.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhudongao
 * Desc
 * Date 4/13/21
 */

public class SPLightUtils {

    private static SharedPreferences sp;
    private static SharedPreferences.Editor editor;

    public static SharedPreferences init(Context context) {
        if (sp == null) {
            sp = context.getSharedPreferences("SpLightUtils", Context.MODE_PRIVATE);
            editor = sp.edit();
        }
        return sp;
    }

    public static <K,T> void setMap(String key , Map<K,T> map){
        if (map == null || map.isEmpty()){
            return;
        }

        Gson gson = new Gson();
        String strJson  = gson.toJson(map);
        if (editor == null) {
            return;
        }
        editor.clear();
        editor.putString(key ,strJson);
        editor.commit();
    }

    public static  <K,T> Map<K,T> getMap(String key){
        Map<K,T> map = new HashMap<>();
        String strJson = sp.getString(key,null);
        if (strJson == null){
            return map;
        }
        Gson gson = new Gson();
        map = gson.fromJson(strJson,new TypeToken<Map<K,T> >(){}.getType());
        return map;
    }
}
